<template>

  <div class="vxe-container">
    <div>
      <el-row>
        <!-- :is-add-show="!!(limits.length >=1 && limits.filter(it => it.FName === '新增').length)"
          :is-edit-show="!!(limits.length >=1 && limits.filter(it => it.FName === '修改').length)"
          :is-del-show="!!(limits.length >=1 && limits.filter(it => it.FName === '删除').length)" -->
        <BHeaderButton
          :is-add-show="isAddShow"
          :is-edit-show="false"
          :is-del-show="true"
          :is-refresh-show="true"
          :is-send-sms-show="false"
          :is-u8-show="false"
          :lists="options"
          :is-back-show="true"
          :is-settings-show="lookSetShow"
          @onAdd="vxeAdd(-1)"
          @onSave="vxeSave"
          @onDelete="vxeDel"
          @onU8="vxeU8"
          @onGoBack="goBack"
          @onRefresh="refresh"
          @onSendSms="vxeSendSms"
          @selectSettings="selectSettings" />

      </el-row>

      <br>

      <!-- 参数配置 -->
      <el-dialog
        v-el-drag-dialog
        :visible.sync="configModal"
        :close-on-click-modal="false"
        width="85%"
        class="config-dialog">
        <head-table :config-list="configList" :key-value="key" @updateConfigData="getUpdateConfigData" />
      </el-dialog>

      <!-- SQL弹窗 -->
      <el-dialog v-el-drag-dialog :visible.sync="dialogSQLModal" :append-to-body="true" title="执行结果">
        <el-form v-loading="loadingFormSQL" ref="formSQL" :rules="rulesSQL" :model="formSQL" label-width="120px">
          <el-form-item label="SQL语句" prop="gzsql">
            <el-input v-model="formSQL.gzsql" :autosize="{ minRows: 14 }" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button :loading="loadingFormSQL" type="primary" @click="confirmSQL">确认</el-button>
            <el-button @click="dialogSQLModal = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- SendMsg弹窗 -->
      <el-dialog v-el-drag-dialog :visible.sync="dialogSendMsgModal" :append-to-body="true" width="50%" title="发送信息">
        <el-tree
          ref="selectTree"
          :props="defaultProps"
          :data="sendUsrList"
          node-key="id"
          show-checkbox
          @node-click="handleNodeClick"/>

        <br>

        <el-form ref="formSendMsg" :rules="rulesSendMsg" :model="formSendMsg" label-width="40px">
          <el-form-item label="内容" prop="fcontent">
            <el-input v-model="formSendMsg.fcontent" :autosize="{ minRows: 5 }" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button :loading="loadingFormSendMsg" type="primary" @click="confirmSendMsg">确认</el-button>
            <el-button @click="dialogSendMsgModal = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>
    <!-- style=" border:1px solid red;width:100%" -->
    <div style=" margin-top:-20px; ">

      <vxe-grid
        ref="xGrid"
        :stripe="false"
        v-bind="gridOptions"
        :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
        :footer-cell-class-name="footerCellClassName"
        @edit-closed="cellClosed"
        @cell-dblclick="cellDbclick"
        @toolbar-button-click="toolbarButtonClickEvent">

        <template #toolbar_buttons />

        <!-- <template #pager>
          <vxe-pager
            :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            :current-page.sync="tablePage.currentPage"
            :page-size.sync="tablePage.pageSize"
            :total="tablePage.total"
            @page-change="handlePageChange" />
        </template> -->
      </vxe-grid>

      <el-dialog
        v-el-drag-dialog
        :visible.sync="fmodelModal"
        :close-on-click-modal="false"
        class="config-dialog fmd-dialog">
        <el-input v-model="fmdFmodel" clearable placeholder="搜索" style="width: 160px;" @keyup.native.enter="searchFmodel" @change="searchFmodel" />
        <el-button type="primary" @click="searchFmodel">搜索</el-button>
        <el-button type="primary" @click="fmdConfirm">确定</el-button>
        <el-table
          v-loading="fTableLoading"
          v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
          ref="fmdTable"
          :data="fmdTableData"
          :summary-method="getSummaries"
          :header-cell-style="tableHeaderStyle"
          show-summary
          class="tableCss single-select-table"
          element-loading-text="正在加载"
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
          @current-change="salaryCurrentChange">
          <el-table-column
            type="selection"
            width="55"/>
          <template v-for="item in fmdThead">
            <el-table-column v-if="item.frpttypeflag ==0" :key="item.fid" :label="item.frepcap" :prop="item.frepfld" :width="item.frepwid" align="center" show-overflow-tooltip>

              <template slot-scope="scope">
                <template v-if="item.frephide<=0">
                  <template v-if="item.frepfld === 'fstatus'">
                    <el-tag v-if="Number(scope.row[item.frepfld]) === 1" size="mini" type="success">已审</el-tag>
                    <el-tag v-else size="mini" type="danger">未审</el-tag>
                  </template>
                  <template v-else size="mini">
                    {{ scope.row[item.frepfld] }}
                  </template>
                </template>
              </template>

            </el-table-column>
          </template>
        </el-table>

        <el-pagination
          v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
          :total="fmdTotal"
          :page-sizes="fmdPagesizes"
          :page-size="fmdPagesize"
          :current-page.sync="fmdCurrentPage"
          class="jy-pagination"
          style="text-align: center; margin-top: 20px;"
          background
          layout="sizes, prev, pager, next, total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>

      </el-dialog>
    </div>

  </div>

</template>
<script>
let FRepKey = ''
// let opername = ''
let fid = ''

import XEUtils from 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'
import { vxetableBillConfig, vxetableGenAdd, tableConfig, apiSql, apiFileSave, XsbList, getDanHao, billGenAdd, admin } from '../../api/account'
import { configColumn, checkStatus } from '../../api/salary'
import { genList } from '../../api/gen'
import { sendsms, beijianTree, billGenEdit, getU8, getJSModelData } from '../../api/peijian'
import { common } from '../../mixins/common'
import { ZeroIsNotDisplay } from '../../utils/index'
import VXETablePluginShortcutKey from 'vxe-table-plugin-shortcut-key'
import '../../styles/vxetable.scss'
import HeadTable from '../salary/headTable/Billindex.vue'

VXETable.use(VXETablePluginShortcutKey, {
  // 功能键设置
  setting: {
    'table.edit.tab.rightMove': 'Enter',
    'table.edit.tab.leftMove': 'shift + Tab'

  }
})

export default {
  components: {
    HeadTable
  },
  filters: {
    ZeroIsNotDisplay(num, n) {
      return ZeroIsNotDisplay(num, n)
    }
  },
  mixins: [common],
  data() {
    return {
      isAddShow: true,
      formData: {

      },
      dialogThead: [],
      columnHeaderData: [],
      columnData: [],
      opername: '',
      aaValue: '',
      oriColumnData: [],

      configList: [],
      configModal: false,
      menusList: [],
      limits: [],
      options: [],
      lookSetShow: false,
      key: 0,
      dialogSQLModal: false,
      loadingFormSQL: false,
      formSQL: {
        gzsql: ''
      },
      rulesSQL: {
      },

      dialogSendMsgModal: false,
      loadingFormSendMsg: false,
      userList: [],
      sendUsrList: [],
      formSendMsg: {

      },
      rulesSendMsg: {

      },
      // mulSendMsgSelect: [],
      // pagesizes: [20, 50, 100, 300, 500],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 20
      },
      vxeDisabled: false,

      keyword: '',
      isHebing: '0',
      gridOptions: {
        border: true,
        showHeaderOverflow: true,
        showOverflow: true,
        showFooterOverflow: true,
        keepSource: true,
        autoResize: true,
        resizable: true,

        height: this.heightGD(),
        showFooter: true,
        round: true,
        size: 'mini',

        id: 'full_edit_1',
        rowId: 'id',
        rowConfig: {
          isHover: true,
          isCurrent: true
        },
        // columnConfig: {
        //   resizable: true
        // },

        // 自定义列配置项
        customConfig: {
          storage: true,
          checkMethod: this.checkColumnMethod
        },

        keyboardConfig: {
          isEnter: true,
          isArrow: true
        },
        editRules: {
          // fcustomer: [
          //   { required: true, message: '不能为空' }
          // ],
          // fmodelno: [
          //   { required: true, message: '不能为空' }
          // ],
          // fmodel: [
          //   { required: true, message: '不能为空' }
          // ],
          // fsxtaishu: [
          //   { required: true, message: '不能为空' }
          // ],
          // fsjpower: [
          //   { required: true, message: '不能为空' }
          // ],
          // fhtpower: [
          //   { required: true, message: '不能为空' }
          // ]
        },
        // formConfig: {
        //   titleWidth: 100,
        //   titleAlign: 'right',
        //   items: [
        //     // { field: 'name', title: '名称', span: 8, titlePrefix: { message: 'app.body.valid.rName', icon: 'vxe-icon-info-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入名称' }}},
        //     // { field: 'email', title: '邮件', span: 8, titlePrefix: { useHTML: true, message: '点击链接：<a class="link" href="https://vxetable.cn" target="_blank">vxe-table官网</a>', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入邮件' }}},
        //     // { field: 'nickname', title: '昵称', span: 8, itemRender: { name: '$input', props: { placeholder: '请输入昵称' }}}
        //     // { field: 'role', title: '角色', span: 8, folding: true, itemRender: { name: '$input', props: { placeholder: '请输入角色' }}},
        //     // { field: 'sex', title: '性别', span: 8, folding: true, titleSuffix: { message: '注意，必填信息！', icon: 'vxe-icon-info-circle-fill' }, itemRender: { name: '$select', options: [] }},
        //     // { field: 'age', title: '年龄', span: 8, folding: true, itemRender: { name: '$input', props: { type: 'number', min: 1, max: 120, placeholder: '请输入年龄' }}}
        //     // { span: 24, align: 'center', collapseNode: true, itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '搜索', status: 'primary' }}, { props: { type: 'reset', content: '重置' }}] }}
        //   ]
        // },

        toolbarConfig: {
          // custom: true,
          buttons: [
            // { code: 'myInsert', name: '新增', icon: 'vxe-icon-square-plus', status: 'success' },
            // { code: 'myDelete', name: '删除', icon: 'vxe-icon-delete', status: 'success' },
            // { code: 'mySave', name: '保存', icon: 'vxe-icon-save', status: 'success' }
            // { code: 'myInsertTZ', name: '新增跳转', icon: 'vxe-icon-square-plus', status: 'success' }
            // { code: 'myOper', name: '操作', icon: 'vxe-icon-square-down', status: 'success', slots: 'default', dropdowns: [{ code: 'myAA', 'name': 'AA', status: 'info', icon: 'vxe-icon-square-plus-fill' }, { code: 'myBB', 'name': 'BB', status: 'info', icon: 'vxe-icon-square-plus-fill' }] }
          ],
          slots: {
            buttons: 'toolbar_buttons'
          }

        },
        columns: [],
        data: [],

        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },

        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true, // 是否显示单元格新增与修改状态
          showIcon: false // 是否显示列头编辑图标
          // activeMethod: this.activeRowMethod
        }

      },

      fmodel: '',
      fmodelData: [],
      fmodelModal: false,
      fmodelLoading: false,
      fmodelId: '',
      setConfigData: {},

      // 分页相关变量
      fmdTotal: 0,
      fmdCurrentPage: 1, // currentPage
      fmdPagesize: 20, // pagesize
      fmdPagesizes: [20, 50, 100, 300, 500, 1000, 2000, 3000, 5000, 10000],
      fTableLoading: false, // listLoading
      fmdThead: [], // formThead
      fmdDialogThead: [], // dialogThead
      fmdColumnData: [], // oriColumnData
      // 批量删除
      fmdCheckData: [], // checkData
      fmdSelectedData: [], // selectedData
      fmdCurData: {}, // curData: {},
      // 导出相关 显示的表头键值对
      fmdHeader: [], // 表头字段（值） // header
      fmdHeaderKeys: [], // 表头字段（键） // headerKeys
      fmdListData: [], // 表体数据 // listData
      fmdTableData: [], // tableData
      fmdTableList: [], // tableList
      rows: [],
      fmdFmodel: ''

    }
  },
  computed: {

  },
  async mounted() {
    await this.getHzAllData()
  },
  async created() {
    FRepKey = this.$route.query.key
    fid = Number(this.$route.query.fid)
    // 这里有fid -- 修改
    // opername = decodeURIComponent(this.globalDb.fname)
    this.opername = decodeURIComponent(this.globalDb.fname)

    // await this.getAdmin()

    await this.getvxetableBillConfig()
    // await this.getModalData()
    // await this.getHzAllData()

    if (fid) {
      this.isAddShow = false
      await this.getBillGenEdit()
      // $grid.insertAt(row, -1)
    } else {
      const $grid = this.$refs.xGrid
      for (let i = 0; i < 1; i++) {
        setTimeout(() => {
          $grid.insertAt(-1, -1)
        }, 0)
      }
      console.log(fid, ' fid')
      // await this.getvxetableGenList()
      // await this.getliushuihao()
    }

    this.lookSetShow = JSON.parse(localStorage.getItem('flookSet'))

    // 菜单列表（权限）
    const menuRes = JSON.parse(localStorage.getItem('setMenuData'))
    this.menusList = menuRes

    if (menuRes.length >= 1) {
      menuRes.map(it => {
        it.children.map(item => {
          if (item.fobjectid === parseInt(FRepKey)) {
            this.$set(this, 'limits', item.child)
          }
        })
      })
    }

    // 参数设置
    const setConfigData = JSON.parse(localStorage.getItem('setConfigData'))
    this.$set(this, 'setConfigData', setConfigData)
    this.setConfigData = setConfigData

    // console.log(menuRes, this.limits, 888888)
  },
  methods: {
    activeRowMethod({ row, column, columnIndex }) {
      console.log(10000, row, column, columnIndex)
    },
    async searchFmodel() {
      // await this.getModalData()
      await this.getHzAllData()
    },
    async getModalData() {
      const res = await getJSModelData({
        opername: decodeURIComponent(this.globalDb.fname),
        fmodel: this.fmodel
      })
      this.fmodelLoading = true
      if (res.Error === 0) {
        this.fmodelLoading = false
        this.fmodelData = res.Data
      }
    },
    selectChangeEvent({ row, column }) {
      // console.log(column.title, 'column.title')
      // console.log(column.field, 'column.field')
      // console.log({ ...column })
      // console.log({ ...row })
      // const $grid = this.$refs.xGrid
      // const index = $grid.getRowid(row)
      // console.log(index)
      // console.log($grid.getEditRecord())
      // console.log($grid.getSelectedCell())
      // $grid.clearSelected()
    },
    formatField(value) {
      // console.log(value, ' formatField')
      if (value) {
        console.log(value, ' formatField')
        return value
      }
      // const item = this.ptypeList.find(item => item.value === value)
      // return item ? item.label : value
    },
    editActive({ row }) {
      console.log(row, ' row')
    },
    // 获取流水号
    async getliushuihao() {
      const res = await getDanHao({
        db: this.globalDb.db,
        opername: this.opername,
        FRepKey
      })
      setTimeout(() => {
        this.$set(this.formData, 'fbillno', res.Data)
        console.log(this.formData, 'this.formData getliushuihao')
      }, 0)
      // this.formData.fbillno = res.Data
    },

    editDisabledEvent({ row }) { },

    editClosedEvent({ row }) { },

    // 高度
    heightGD() {
      return (document.body.offsetHeight - 185) + 'px'
    },
    selectSettings(val) {
      if (val === 0) {
        this.settings()
      } else if (val === 1) {
        this.dialogSQL()
      }
    },
    settings() {
      this.configModal = true
      this.getTableConfig()
    },
    async getTableConfig() {
      try {
        this.configLoading = true
        const res = await tableConfig({
          db: this.globalDb.db,
          opername: this.opername,
          key: FRepKey,
          billtype: 1
        })
        this.configList = res.Data
        this.key = FRepKey
        this.configLoading = false
      } catch (error) {
        this.configLoading = false
      }
    },

    // SQL修改/更新
    async dialogSQL() {
      this.dialogSQLModal = true
      try {
        const res = await apiSql({
          db: this.globalDb.db,
          opername: this.opername,
          type: 1,
          FRepKey
        })

        if (res.Error === 0) {
          this.formSQL.gzsql = res.Data
          this.formSQL.FRepKey = FRepKey
        }
        setTimeout(() => {
          this.$refs['formSQL'].clearValidate()
        })
      } catch (error) {
        // console.log(error)
      }
    },

    confirmSQL() {
      this.$refs['formSQL'].validate(async(valid) => {
        if (valid) {
          try {
            this.formSQL.db = this.globalDb.db
            this.formSQL.opername = this.opername
            this.formSQL.type = 1
            const res = await apiFileSave(this.formSQL)
            if (res.Error === 0) {
              this.dialogSQLModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            // console.log(error)
          }
        } else {
          return false
        }
      })
    },

    // 更新数据
    async getUpdateConfigData() {
      await this.getTableConfig()
    },
    cellDbclick({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) {
      if (column.field === 'fmodel') {
        this.fmodelId = row.id
        this.fmodelModal = true
      }
    },
    cellClosed({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
      const $grid = this.$refs.xGrid
      const { tableData } = $grid.getTableData()
      tableData.map(it => {
        if (it.id === row.id) {
          const cyAll = Number(row.fcyqty) * Number(row.fcyprice)
          this.$set(it, 'fcyamount', ZeroIsNotDisplay(cyAll, 2)) // 柴油金额
          const qgAll = Number(row.fqgyqty) * Number(row.fqgyprice)
          this.$set(it, 'fqgyamount', ZeroIsNotDisplay(qgAll, 2)) // 气缸油金额
          const rqAll = Number(row.ftrqqty) * Number(row.ftrqprice)
          this.$set(it, 'ftrqamount', ZeroIsNotDisplay(rqAll, 2)) // 天然气金额
          this.$set(it, 'fallamount', ZeroIsNotDisplay(cyAll + qgAll + rqAll, 2)) // 合计金额
        }
      })
    },
    // 添加表格背景颜色
    footerCellClassName({ $rowIndex, columnIndex }) {
      // if (columnIndex === 0) {
      if ($rowIndex === 0) {
        // return 'col-blue'
        // }
      }
    },

    // 字段
    async getvxetableBillConfig() {
      const res = await vxetableBillConfig(
        {
          FUnControl: -1,
          opername: this.opername,
          FRepKey,
          FRepPage: 1

        }
      )
      this.oriColumnData = res.Data
      const dataVxe = []
      // setTimeout(() => {
      if (res.Data.length > 0) {
        this.columnData.push({
          type: 'seq',
          width: 50,
          fixed: 'left'
        })
        // this.columnData.push({
        //   type: 'checkbox',
        //   width: 50,
        //   fixed: 'left'
        // })

        for (let i = 0; i < res.Data.length; i++) {
          // FRepType 202, 200 -- 文本， 131 --数值 ，135 -- 日期
          if (res.Data[i].fheaderfooter === 1) {
            // 表体字段
            if (res.Data[i].falign === 1) {
              this.columnData.push({
                field: res.Data[i].frepfld,
                title: res.Data[i].frepcap,

                headerAlign: 'left',
                align: 'right',

                width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                editRender: { name: 'input', attrs: { disabled: Boolean(res.Data[i].fisedit), placeholder: '' }}
              })
            } else {
              this.columnData.push({
                field: res.Data[i].frepfld,
                title: res.Data[i].frepcap,
                // showHeaderOverflow: true,
                // showOverflow: true,
                // resizable: true,
                width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                editRender: { name: 'input', attrs: { disabled: Boolean(res.Data[i].fisedit), placeholder: '' }}
              })
            }
          } else {
            // 表头
            this.dialogThead.push(res.Data[i])
            // columnHeaderData
            this.columnHeaderData.push({
              field: res.Data[i].frepfld,
              title: res.Data[i].frepcap,
              // showHeaderOverflow: true,
              // showOverflow: true,
              // resizable: true,
              titleColon: true,
              titleWidth: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0

            })

            // this.$set(this.formData, i, data[i])
            // this.formData.items = this.columnHeaderData
          }
        }
        // console.log(this.dialogThead, this.columnHeaderData)+
        //    for (const i in data) {
        //   this.$set(this.form, i, data[i])
        // }

        this.dialogThead.map(item => { dataVxe[item.frepfld] = '' })
        for (const i in dataVxe) {
          this.$set(this.formData, i, dataVxe[i])
        }

        console.log(this.columnData, ' this.columnData')

        this.gridOptions.columns = this.columnData
      }
      // }, 1000)
    },

    // formatFstatus(row) {
    //   console.log(row, 88888888888)

    //   }
    // },

    async vxeU8() {
      const res = await getU8({
        opername: decodeURIComponent(this.globalDb.fname),
        fbillno: this.formData.fbillno,
        FRepKey
      })
      if (res.Error === 0) {
        this.$message({
          message: '同步成功',
          type: 'success'
        })
        this.gridOptions.data = res.Data
        const $grid = this.$refs.xGrid
        for (let i = 0; i < 100; i++) {
          setTimeout(() => {
            $grid.insertAt(-1, -1)
          }, 0)
        }
      } else {
        this.$message({
          message: '失败',
          type: 'error'
        })
      }
    },
    goBack() {
      this.$router.push('/jzgl/icerrqbyq')
    },

    // 发送信息
    async vxeSendSms() {
      this.dialogSendMsgModal = true
      await this.getBeijianTree()
    },
    handleNodeClick(data) {
      console.log(data)
    },
    async confirmSendMsg() {
      const selectMsgArr = this.$refs.selectTree.getCheckedKeys(true)
      this.dialogSendMsgModal = true
      try {
        const fcontent = this.formSendMsg.fcontent
        const fbillno = this.formData.fbillno
        if (selectMsgArr.length) {
          const fid = selectMsgArr.join(',')
          if (!fid) {
            this.$message({
              message: '手机号为空',
              type: 'error'
            })
            return
          }

          const res = await sendsms({
            opername: decodeURIComponent(this.globalDb.fname),
            fid,
            fcontent,
            fbillno
          })
          console.log(res, ' res')
          if (res.Error === 0) {
            this.mulSendMsgSelect = []
            this.formSendMsg.fcontent = ''
            this.dialogSendMsgModal = false
          }
        } else {
          this.$message({
            message: '未选中发送信息通知人员',
            type: 'error'
          })
          return
        }
      } catch (error) {
        this.dialogSendMsgModal = false
      }
    },
    async getBeijianTree() {
      try {
        this.sendMsgLoading = true
        const res = await beijianTree({
          opername: decodeURIComponent(this.globalDb.fname)
        })
        console.log(res, ' res')

        this.sendUsrList = res.Data
        this.sendMsgLoading = false
      } catch (error) {
        this.sendMsgLoading = false
        console.log(error)
      }
    },
    async getAdmin() {
      try {
        this.sendMsgLoading = true
        const res = await admin({
          db: this.globalDb.db,
          opername: this.loginname,
          keyword: this.keyword,
          username: this.loginname,
          limit: this.pagesize,
          page: this.currentPage
        })
        this.userList = res.result
      } catch (error) {
        console.log(error)
      }
    },
    // 刷新
    refresh() {
      window.location.reload()
    },

    // 新增
    vxeAdd(row) {
      console.log(row, 'row')
      const $grid = this.$refs.xGrid
      $grid.insertAt(row, -1)
      // const total = 50
      // for (var i = 0; i <= total; i++) {
      //   $grid.insert({})
      // }
    },

    // 保存
    async vxeSave() {
      const $grid = this.$refs.xGrid
      const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
      const { tableData } = $grid.getTableData()
      //  console.log(insertRecords, removeRecords, updateRecords, 111111, this.formData)
      if (insertRecords.length === 0 && updateRecords.length === 0 && removeRecords.length === 0) {
        VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'warning' })
        return
      }
      // 修改时 是否已审核
      if (updateRecords.length > 0) {
        const isFstatus = updateRecords.filter(it => Number(it.fstatus) === 1)
        if (isFstatus.length) {
          this.$message({
            message: '已审核，不能修改！',
            type: 'error'
          })
          return
        }
      }

      const insertRecordsArr = []
      insertRecords.map(it => {
        if (it.fmodel) {
          insertRecordsArr.push(it)
        }
      })
      const tableDataArr = []
      tableData.map(it => {
        if (it.fmodel) {
          tableDataArr.push(it)
        }
      })

      try {
        const res = await billGenAdd({
          FRepKey,
          opername: this.opername,
          insertRecords: insertRecordsArr,
          updateRecords,
          removeRecords,
          tableData: tableDataArr,
          formdata: this.formData
        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
          this.goBack()
        }

        // this.getvxetableGenList()
      } catch (error) {
        console.log(error)
      }

      // VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'success' })
    },

    // 删除
    async vxeDel() {
      // console.log(11111)
      const $grid = this.$refs.xGrid

      // 删除当前行    VXETable.modal.alert($grid.getCurrentRecord())
      $grid.remove($grid.getCurrentRecord())

      // if ($grid.getCheckboxRecords().length === 0) {
      //   VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
      //   return
      // }

      // 判断已审核
      // const dataTemp = $grid.getCheckboxRecords()
      // const isFstatus = dataTemp.filter(it => Number(it.fstatus) === 1)
      // if (isFstatus.length) {
      //   this.$message({
      //     message: '已审核，不能删除！',
      //     type: 'error'
      //   })
      //   return
      // }

      // const { removeRecords } = $grid.getRecordset()

      // const res = await vxetableGenAdd({ FRepKey, opername: this.opername, removeRecords })
      // if (res.Error === 0) {
      //   VXETable.modal.message({ content: ` 删除 ${removeRecords.length} 条`, status: 'success' })
      //   this.getvxetableGenList()
      // }
    },

    // 1—审核，0—反审
    async check(Fstatus) {
      const $grid = this.$refs.xGrid
      if ($grid.getCheckboxRecords().length === 0) {
        VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
        return
      }
      const checkData = []
      $grid.getCheckboxRecords().map(it => {
        checkData.push(it.fid)
      })

      if (Number(Fstatus) === 1) {
        this.$confirm('是否审核, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        }).then(async() => {
          try {
            const res = await checkStatus({
              db: this.globalDb.db,
              opername: decodeURIComponent(this.globalDb.fname),
              loginname: decodeURIComponent(this.globalDb.fname),
              FRepKey,
              Fstatus, // 1—审核，0—反审
              fid: checkData.join(',')

            })
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              await this.getvxetableGenList()
            } else {
              this.loadingForm = false
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            console.log(error)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        try {
          const res = await checkStatus({
            db: this.globalDb.db,
            opername: decodeURIComponent(this.globalDb.fname),
            loginname: decodeURIComponent(this.globalDb.fname),
            FRepKey,
            Fstatus, // 1—审核，0—反审
            fid: checkData.join(','),
            appname: ''
          })
          if (res.Error === 0) {
            this.$message({
              message: res.Message,
              type: 'success'
            })
            await this.getvxetableGenList()
          } else {
            this.loadingForm = false
            this.$message({
              message: res.Message,
              type: 'error'
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
    },

    // 内容列表
    async getvxetableGenList() {
      const param = { opername: decodeURIComponent(this.globalDb.fname), FRepKey, keyword: this.keyword, isHebing: this.isHebing, fstatus: this.fstatus, page: this.tablePage.currentPage, pageSize: this.tablePage.pageSize }
      const res = await XsbList(param)
      setTimeout(() => {
        this.tablePage.total = res.total
        this.gridOptions.data = res.Data
        // res.Data
      }, 0)
    },
    // 编辑内容设置
    async getBillGenEdit() {
      const param = { FRepKey, fid, opername: this.opername }
      const res = await billGenEdit(param)
      setTimeout(() => {
        if (res.Data && res.Data.length) {
          this.gridOptions.data = res.Data
          this.$set(this.formData, 'fbillno', res.Data[0].fbillno)
          this.$set(this.formData, 'fchuanmin', res.Data[0].fchuanmin)
          this.$set(this.formData, 'fchuanhao', res.Data[0].fchuanhao)
          this.$set(this.formData, 'fmodel', res.Data[0].fmodel)
          this.$set(this.formData, 'fprodectno', res.Data[0].fprodectno)
          this.$set(this.formData, 'fcustomer', res.Data[0].fcustomer)
        }
      }, 0)
    },
    // 分页
    handlePageChange({ currentPage, pageSize }) {
      console.log(22222, currentPage, pageSize)
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.getvxetableGenList()
    },

    addressClickEvent(row) {
      VXETable.modal.alert(`address点击事件：${row.address}`)
    },

    // 按钮点击
    async toolbarButtonClickEvent({ code }) {
      console.log(code, 'code toolbarButtonClickEvent')
      const $grid = this.$refs.xGrid
      switch (code) {
        case 'myInsert':
          console.log(234, $grid)
          $grid.insert({

          })
          break
        // 保存
        case 'mySave':
          setTimeout(async() => {
            const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()

            if (insertRecords.length === 0 && updateRecords.length === 0 && removeRecords.length === 0) {
              VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'warning' })
              return
            }
            console.log(insertRecords, removeRecords, updateRecords, insertRecords.length > 0, updateRecords.length > 0, removeRecords.length > 0)
            try {
              const res = await vxetableGenAdd({ FRepKey, opername: this.opername, insertRecords, updateRecords, removeRecords })
              if (res.Error === 200) {
                this.getvxetableGenList()
                VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'success' })
              } else {
                VXETable.modal.message({ content: res.Message, status: 'error' })
              }
            } catch (error) {
              console.log(error)
            }
          })
          break
        // 删除
        case 'myDelete':
          if ($grid.getCheckboxRecords().length === 0) {
            VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
            return
          }
          setTimeout(async() => {
            const { removeRecords } = $grid.getRecordset()

            $grid.removeCheckboxRow()
            const res = await vxetableGenAdd({ FRepKey, opername: this.opername, removeRecords })
            if (res.Error === 0) {
              VXETable.modal.message({ content: ` 删除 ${removeRecords.length} 条`, status: 'success' })
              this.getvxetableGenList()
            }

            // $grid.clearSelected()
            // $grid.clearCheckboxRow()
          })
          break

        case 'myInsertTZ':

          break

        case 'myAA':
          VXETable.modal.message({ content: '新增', status: 'success' })
          break
      }
    },

    sumNum(list, field) { // DONE
      let count = 0
      list.forEach(item => {
        count += Number(item[field]) * 100
      })
      return (count / 100)
    },
    // 合计
    footerMethod({ columns, data }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        this.aaValue = ''
        if (columnIndex === 0) {
          sums.push('合计')
        } else {
          this.oriColumnData.forEach((item, itemIndex) => {
            if (column.property === item.frepfld && item.frepsum === 1) {
              this.aaValue = item.frepfld
              return false
            }
          })
          if (column.property === this.aaValue) {
            sums.push(this.sumNum(data, column.property))
          } else {
            sums.push('')
          }
        }
      })
      // 返回一个二维数组的表尾合计
      return [sums]
    },

    formatAmount({ cellValue }) {
      return cellValue ? `￥${XEUtils.commafy(XEUtils.toNumber(cellValue), { digits: 2 })}` : ''
    },
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:ss:mm')
    },
    checkColumnMethod({ column }) {
      if (['nickname', 'role'].includes(column.property)) {
        return false
      }
      return true
    },

    // 合计
    getSummaries({ columns, data }) {
      const sums = []
      const arr = []
      this.fmdColumnData.forEach((item, itemIndex) => {
        if (item.frepfld && item.frepsum === 1) {
          arr.push(item.frepfld)
        }
      })
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums[columnIndex] = '合计'
        } else {
          if (arr.indexOf(column.property) >= 0) {
            sums[columnIndex] = this.fmdSumNum(data, column.property)
          } else {
            sums[columnIndex] = ''
          }
        }
      })
      // 返回一个二维数组的表尾合计
      return sums
    },
    fmdSumNum(list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    },
    handleSelectionChange(rows) {
      if (rows.length) {
        this.rows = rows
      }
      if (rows.length > 1) {
        this.$refs.fmdTable.clearSelection()
        this.$refs.fmdTable.toggleRowSelection(rows.pop())
      }
    },
    salaryCurrentChange(val) {
      this.fmdCurData = val
    },
    async handleSizeChange(val) {
      this.fmdCurrentPage = 1
      this.fmdPagesize = val
      await this.getHzAllData()
    },
    async handleCurrentChange(val) {
      this.fmdCurrentPage = val
      await this.getHzAllData()
    },
    async getHzAllData() {
      await this.getBodyData()
      await this.getHeadData()
    },
    // 表头数据
    async getHeadData() {
      try {
        this.fTableLoading = true
        // this.fmdHeader = []
        // this.fmdHeaderKeys = []
        // this.fmdListData = []
        const res = await configColumn({
          db: this.globalDb.db,
          opername: this.opername,
          FRepKey: 29001
        })
        this.fTableLoading = false
        this.fmdThead = res.Data
        this.fmdColumnData = res.Data
        this.fmdThead.map(item => {
          this.fmdTableList.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })
        this.fmdTableData = this.fmdTableList.slice()
        // 获取显示表头键值对
        this.fmdThead.filter(item => {
          if (!item.frephide) {
            this.fmdHeader.push(item.frepcap)
            this.fmdHeaderKeys.push(item.frepfld)
          }
        })
        // 获取显示表体数据
        const listData = this.fmdTableList.slice()
        listData.map((item, index) => {
          this.fmdListData[index] = {}
          this.fmdHeaderKeys.map(it => {
            this.fmdListData[index][it] = item[it]
          })
        })
        // 去除内码
        const arr = res.Data.slice()
        arr.map((item, index) => {
          if (item.frepfld === 'fid') {
            arr.splice(index, 1)
          }
        })
        this.fmdDialogThead = arr.filter(item => item.funcontrol !== 1)
      } catch (error) {
        this.fTableLoading = false
      }
    },
    // 表体数据————erp职员列表
    async getBodyData() {
      try {
        this.fTableLoading = true
        const res = await genList({
          db: this.globalDb.db,
          opername: this.opername,
          keyword: this.keyword,
          fstatus: this.fstatus,
          limit: this.fmdPagesize,
          page: this.fmdCurrentPage,
          FRepKey: 29001
        })
        this.fTableLoading = false
        this.fmdTableList = res.Data
        this.fmdTotal = res.total
      } catch (error) {
        this.fTableLoading = false
      }
    },
    tableClick(row, column, event) {
      console.log(row, ' row')
      this.detailRes = row
      this.jxModel = true
      this.hz2TableData = [{
        // 'rownumber': '1',
        // 'fid': 21,
        // 'fmodel': '6X40-B',
        // 'fbillno': 'YC20221216000021',
        // 'fcreatetime': '2023-02-16 17:04:39',
        // 常规机
        // 常规机带HPSCR/LPSCR/EGRBP
        // 常规机带EcoEGR
        // <td>双燃料DF机</td>
        // 'fstranyoucgj': '102899.82',
        // 'fstranyoucgjscr': '196588.94',
        // 'fstranyoucgjegr': '295796.68',
        // 'fstranyousyldf': '164401.12',
        // 'fstranyousylicer': '175259.54',
        // 'fstranqisyldf': '61501.30',
        // 'fstranqisylicer': '123371.36',
        // 'fstqigangyoucgj': '520.87',
        // 'fstqigangyoucgjscr': '960.73',
        // 'fstqigangyoucgjegr': '1460.93',
        // 'fstqigangyousyldf': '885.11',
        // 'fstqigangyousylicerry': '1620.15',
        // 'fstqigangyousylicerrq': '1252.15',
        // 'fstniaosucgjscr': '15480.00',
        // 'fstnaohcgjegrbp': '2263.50',
        // 'fstnaohcgjecoegr': '4527.00',
        // 'fstnaohsrlicerry': '3755.50',
        // 'fstnaohsrlicerrq': '1899.00',
        // 'fnostranyoucgjscr': '182139.44',
        // 'fnostranyoucgjegr': '278632.78',
        // 'fnostranyousyldf': '158176.72',
        // 'fnostranyousylicer': '168684.14',
        // 'fnostranqisyldf': '57991.30',
        // 'fnostranqisylicer': '116351.36',
        // 'fnostqigangyoucgj': '508.39',
        // 'fnostqigangyoucgjscr': '895.21',
        // 'fnostqigangyoucgjegr': '1382.93',
        // 'fnostqigangyousyldf': '853.91',
        // 'fnostqigangyousylicerry': '1551.51',
        // 'fnostqigangyousylicerrq': '1202.23',
        // 'fnostniaosucgjscr': '13780.00',
        // 'fnostnaohcgjegrbp': '1966.00',
        // 'fnostnaohcgjecoegr': '3932.00',
        'fnostnaohsrlicerry': '3605.50',
        'fnostnaohsrlicerrq': '1794.00',
        'fpower': '3900',
        'fmoheqigangyouhz': '20.67',
        'fmoheranyouhz': '3692.08',
        'fry29003': '99207.74',
        'fqg29003': '500.20',
        'fnaoh29003': 0,
        'fnory29003': '96493.34',
        'fnoqg29003': '487.72',
        'fnonaoh29003': 0,
        'fry29004': '93689.12',
        'fqg29004': '439.86',
        'fns29004': '15480.00',
        'fnaoh29004': '2263.50',
        'fnory29004': '81954.02',
        'fnoqg29004': '386.82',
        'fnons29004': '13780.00',
        'fnonaoh29004': '1966.00',
        'fry29005': '72359.72',
        'fqg29005': '368.00',
        'fyry29005': 0,
        'fnaoh29005': '1856.50',
        'fnory29005': '68498.72',
        'fnoqg29005': '349.28',
        'fnoyry29005': 0,
        'fnonaoh29005': '1811.50',
        'fry29006': '61501.30',
        'fqg29006': '364.24',
        'fyry29006': 0,
        'fnaoh29006': '1839.00',
        'fnory29006': '57991.30',
        'fnoqg29006': '345.52',
        'fnoyry29006': 0,
        'fnonaoh29006': '1794.00',
        'fry29007': '61870.06',
        'fqg29007': '367.04',
        'fyry29007': 0,
        'fnaoh29007': '1899.00',
        'fnory29007': '58360.06',
        'fnoqg29007': '348.32',
        'fnoyry29007': 0,
        'fnonaoh29007': '1794.00'
        // 'fnostranyoucgj': '100185.42'
        // 'fstatus': 0,
        // 'checkname': ''
      }]
    },
    fmdConfirm() {
      // TODO......
      const $grid = this.$refs.xGrid
      const { tableData } = $grid.getTableData()
      // console.log(this.rows, ' this.rows')
      if (this.rows.length) {
        tableData.map(it => {
          // ICER燃气版油气
          // 柴油数量	                  单价	      柴油金额	 气缸油数量	                单价	       气缸油金额	   天然气数量	              单价	       天然气金额	合计
          // 取技术中心的iCER燃气版油耗	 取基础数据		          取技术中心iCER燃气版的油耗	取基础数据		             取技术中心ICER的燃气	    取基础数据

          // 合计=柴油金额+
          // // 天然气金额+
          // // 气缸油金额

          if (it.id === this.fmodelId) {
            this.$set(it, 'fmodel', this.rows[0].fmodel) // 机型
            this.$set(it, 'fcyqty', 0) // 柴油数量
            this.$set(it, 'fqgyqty', this.rows[0].fstqigangyousylicerrq) // 气缸油数量
            this.$set(it, 'ftrqqty', this.rows[0].fstranqisylicer) // 天然气数量
            this.$set(it, 'fcyprice', this.setConfigData.fsetchaiyouprice) // 柴油单价
            this.$set(it, 'fqgyprice', this.setConfigData.fsetqigangprice) // 气缸油单价
            this.$set(it, 'ftrqprice', this.setConfigData.fsetranqiprice) // 天然气单价
            const cyAll = 0 * Number(this.setConfigData.fsetchaiyouprice)
            const qgAll = Number(this.rows[0].fstqigangyousylicerrq) * Number(this.setConfigData.fsetqigangprice)
            const rqAll = Number(this.rows[0].fstranqisylicer) * Number(this.setConfigData.fsetranqiprice)
            this.$set(it, 'fcyamount', cyAll.toFixed(2)) // 柴油金额
            this.$set(it, 'fqgyamount', qgAll.toFixed(2)) // 气缸油金额
            this.$set(it, 'ftrqamount', rqAll.toFixed(2)) // 天然气金额
            this.$set(it, 'fallamount', (cyAll + qgAll + rqAll).toFixed(2)) // 合计金额
          }
        })
        this.fmodelModal = false
        this.rows = []
        this.$refs.fmdTable.clearSelection()
      }
    }

  }

}

</script>
<style lang="scss" scoped>
.config-dialog ::v-deep .el-dialog {
  width: 70%;
}
.config-dialog ::v-deep .el-dialog__body {
  padding: 0px 20px;
}
.fmd-dialog ::v-deep .el-dialog__body {
  height: 700px;
  max-height: 700px;
}
.fmd-dialog ::v-deep .el-table {
  margin-top: 10px;
}
.fmd-dialog ::v-deep .single-select-table thead .el-table-column--selection .cell {
  display: none;
}
</style>
